local socket = require "socket.core"
local log = require("mylog")

local time = {}

-- 获取当前时间戳毫秒级别
function time.getNowTime()
    return socket.gettime()
end

-- 两个毫米级别时间戳的差值
function time.subTime(firstTime, secondTime)
    return firstTime - secondTime
end

-- 线程休眠：秒
function time.sleep(time)
    os.execute("sleep " .. time)
end

--是微软的时间自动同步服务器的域名。
local server_ip = {
    "time-c.nist.gov",
    "time-nw.nist.gov",
    "time-a.nist.gov",
    "time-b.nist.gov",
    "time.nist.gov",
    "time-d.nist.gov"
}
local function nstol(str)
    assert(str and #str == 4)
    local t = {str:byte(1, -1)}
    local n = 0
    for k = 1, #t do
        n = n * 256 + t[k]
    end
    return n
end

-- 使用tcp协议，从ip地址下获取时间
local function gettime(ip)
    log.info("[gettime] connect ", ip)
    local tcp = socket.tcp()
    tcp:settimeout(10)
    tcp:connect(ip, 37)
    local success, time = pcall(nstol, tcp:receive(4))
    tcp:close()
    return success and time or nil
end

local function nettime()
    for _, ip in pairs(server_ip) do
        local time = gettime(ip)
        if time then
            return time - 2208988800
        end
    end
end

-- 校准时间
function time.calibration_time()
    local realTime = nettime()
    local realTimeStr = os.date("%Y-%m-%d %H:%M:%S", realTime)
    local cmd = "date -s " .. '"' .. realTimeStr .. '"'
    log.debug("[calibration_time] 校验时间命令：", cmd)
    local res = os.execute(cmd)
    if res then
        log.info("校准时间成功！")
        return 0
    else
        log.info("校准时间失败！")
        return 1
    end
end

return time
